import type {AxiosRequestConfig} from 'axios'
import axios from 'axios'

let baseURL: string = import.meta.env.VITE_BASE_URL
let timeout: number = import.meta.env.VITE_REQUEST_TIMEOUT

let axiosInstance = axios.create({
  baseURL,
  timeout
})

// 请求拦截器
axiosInstance.interceptors.request.use(config => {
  return config
})

// 响应拦截器
axiosInstance.interceptors.response.use(
  response => response.data,
  err => {
    console.error(`[${err.code}]:${err.config.baseURL}${err.config.url}`, err)
    return err
  }
)


export default {
  baseURL,
  timeout,
  get(url: string, params?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'get',
      params,
      ...config
    })
  },
  post(url: string, data?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'post',
      data,
      ...config
    })
  },
  put(url: string, data?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'put',
      data,
      ...config
    })
  },
  delete(url: string, data?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'delete',
      data,
      ...config
    })
  }
}